package com.fishingwithme.android.ui.viewmodels

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.fishingwithme.android.data.model.Position
import com.fishingwithme.android.data.model.SpotProperty
import com.fishingwithme.android.data.model.SpotUpdateDTO
import com.fishingwithme.android.data.repository.FishingRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import java.io.File
import javax.inject.Inject

data class SpotUpdateUiState(
    val id: String = "",
    val isLoading: Boolean = false,
    val error: String? = null,
    val props: SpotProperty = SpotProperty(),
    val currentLocation: Position? = null,
    val isSaveSuccess: Boolean = false,
    val spotName: String = "",
    val latitude: Double = 0.0,
    val longitude: Double = 0.0,
    val isFree: Boolean = true,
    val isForbidden: Boolean = false,
    val isPrivate: Boolean = true,
    val parkingEasy: Boolean = true, // 1:方便, 0:不便
    val selectedLevel: String = "",
    val selectedDistance: String = "",
    val selectedWaterType: String = "",
    val selectedSpotType: Set<String> = emptySet(),
    val selectedFishTypes: Set<String> = emptySet(),
    val description: String = "",
    val photos: List<String> = emptyList(),
    val line: List<Position> = emptyList()
)

@HiltViewModel
class SpotUpdateViewModel @Inject constructor(
    private val repository: FishingRepository
) : ViewModel() {
    private val _uiState = MutableStateFlow(SpotUpdateUiState())
    val uiState: StateFlow<SpotUpdateUiState> = _uiState.asStateFlow()

    fun loadSpotData(id: String) {
        viewModelScope.launch {
            _uiState.update { it.copy(isLoading = true, error = null) }
            
            try {
                // Load spot details
                repository.loadUserSpot(id).collect { result ->
                    result.fold(
                        onSuccess = { spotDetail ->
                            _uiState.update { currentState ->
                                currentState.copy(
                                    id = spotDetail.spotId,
                                    spotName = spotDetail.name,
                                    description = spotDetail.description,
                                    latitude = spotDetail.latitude,
                                    longitude = spotDetail.longitude,
                                    isFree = spotDetail.isFree == 1,
                                    isPrivate = spotDetail.isPrivate == 1,
                                    isForbidden = spotDetail.isForbidden == 1,
                                    parkingEasy = spotDetail.parkingEasy == 1,
                                    selectedLevel = spotDetail.lvl.code,
                                    selectedDistance = spotDetail.distance.code,
                                    selectedWaterType = spotDetail.waterType.code,
                                    selectedSpotType = spotDetail.jsonSpotTypes.map { it.code }.toSet(),
                                    selectedFishTypes = spotDetail.jsonFishTypes.map { it.code }.toSet(),
                                    photos = spotDetail.jsonPics,
                                    isLoading = false
                                )
                            }
                        },
                        onFailure = { throwable ->
                            _uiState.update {
                                it.copy(
                                    isLoading = false,
                                    error = throwable.message ?: "加载钓点信息失败"
                                )
                            }
                        }
                    )
                }
            } catch (e: Exception) {
                _uiState.update {
                    it.copy(
                        isLoading = false,
                        error = e.message ?: "未知错误"
                    )
                }
            }
        }
    }

    fun loadProps() {
        viewModelScope.launch {
            _uiState.update { it.copy(isLoading = true) }
            repository.loadAddSpotProperties().collect { result ->
                result.fold(
                    onSuccess = { props ->
                        _uiState.update { it.copy(props = props, isLoading = false) }
                    },
                    onFailure = { throwable ->
                        _uiState.update {
                            it.copy(
                                isLoading = false,
                                error = throwable.message ?: "加载属性失败"
                            )
                        }
                    }
                )
            }
        }
    }

    fun updateSpotName(name: String) {
        _uiState.update { it.copy(spotName = name) }
    }

    fun updateLocation(latitude: Double, longitude: Double) {
        _uiState.update {
            it.copy(
                latitude = latitude,
                longitude = longitude
            )
        }
    }

    fun updatePoints(points: List<Position>) {
        _uiState.update { it.copy(line = points) }
    }

    fun updateIsFree(isFree: Boolean) {
        _uiState.update { it.copy(isFree = isFree) }
    }

    fun updateIsForbidden(isForbidden: Boolean) {
        _uiState.update { it.copy(isForbidden = isForbidden) }
    }

    fun updateIsPrivate(isPrivate: Boolean) {
        _uiState.update { it.copy(isPrivate = isPrivate) }
    }

    fun updateParkingEasy(isEasy: Boolean) {
        _uiState.update { it.copy(parkingEasy = isEasy) }
    }

    fun updateSelectedLevel(level: String) {
        _uiState.update { it.copy(selectedLevel = level) }
    }

    fun updateSelectedDistance(distance: String) {
        _uiState.update { it.copy(selectedDistance = distance) }
    }

    fun updateSelectedWaterType(waterType: String) {
        _uiState.update { it.copy(selectedWaterType = waterType) }
    }

    fun toggleSpotType(typeCode: String) {
        _uiState.update { currentState ->
            val currentTypes = currentState.selectedSpotType.toMutableSet()
            if (currentTypes.contains(typeCode)) {
                currentTypes.remove(typeCode)
            } else {
                currentTypes.add(typeCode)
            }
            currentState.copy(selectedSpotType = currentTypes)
        }
    }

    fun toggleFishType(typeCode: String) {
        _uiState.update { currentState ->
            val currentTypes = currentState.selectedFishTypes.toMutableSet()
            if (currentTypes.contains(typeCode)) {
                currentTypes.remove(typeCode)
            } else {
                currentTypes.add(typeCode)
            }
            currentState.copy(selectedFishTypes = currentTypes)
        }
    }

    fun updateDescription(description: String) {
        _uiState.update { it.copy(description = description) }
    }

    fun updatePhotos(photos: List<String>) {
        _uiState.update { it.copy(photos = photos) }
    }

    suspend fun uploadFile(file: File) = repository.uploadFile(file)

    fun updateSpot() {
        viewModelScope.launch {
            _uiState.update { it.copy(isLoading = true, error = null) }
            
            try {
                // Create SpotUpdateDTO with all the necessary information
                val spotUpdateDTO = SpotUpdateDTO(
                    id = _uiState.value.id,
                    name = _uiState.value.spotName,
                    location = Position(
                        latitude = _uiState.value.latitude,
                        longitude = _uiState.value.longitude
                    ),
                    line = _uiState.value.line,
                    pics = _uiState.value.photos,
                    spotTypes = _uiState.value.selectedSpotType.toList(),
                    fishTypes = _uiState.value.selectedFishTypes.toList(),
                    isFree = _uiState.value.isFree,
                    parkingEasy = _uiState.value.parkingEasy,
                    lvl = _uiState.value.selectedLevel,
                    distance = _uiState.value.selectedDistance,
                    secret = _uiState.value.isPrivate,
                    isForbidden = _uiState.value.isForbidden,
                    waterType = _uiState.value.selectedWaterType,
                    description = _uiState.value.description
                )
                
                repository.updateSpotDetailed(spotUpdateDTO).collect { result ->
                    result.fold(
                        onSuccess = {
                            android.util.Log.d("SpotUpdateViewModel", "Spot update successful")
                            _uiState.update { 
                                it.copy(
                                    isLoading = false,
                                    isSaveSuccess = true
                                )
                            }
                        },
                        onFailure = { throwable ->
                            android.util.Log.e("SpotUpdateViewModel", "Spot update failed: ${throwable.message}")
                            _uiState.update {
                                it.copy(
                                    isLoading = false,
                                    error = throwable.message ?: "更新钓点失败"
                                )
                            }
                        }
                    )
                }
            } catch (e: Exception) {
                android.util.Log.e("SpotUpdateViewModel", "Spot update exception: ${e.message}")
                _uiState.update {
                    it.copy(
                        isLoading = false,
                        error = e.message ?: "未知错误"
                    )
                }
            }
        }
    }

    fun resetSaveState() {
        _uiState.update { it.copy(isSaveSuccess = false) }
    }
}